package cn.com.connext.scrm.service;

import cn.com.connext.scrm.config.Constants;
import cn.com.connext.scrm.domain.master.Member;
import cn.com.connext.scrm.domain.master.MiniProgramUser;
import cn.com.connext.scrm.domain.master.SendRecordEntity;
import cn.com.connext.scrm.repository.master.MemberRepository;
import cn.com.connext.scrm.repository.master.MiniProgramUserRepository;
import cn.com.connext.scrm.repository.master.SendRecordRepository;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.dto.MemberDTO;
import cn.com.connext.scrm.service.dto.SmsDTO;
import cn.com.connext.scrm.service.mapper.MemberMapper;
import cn.com.connext.scrm.utils.MapUtil;
import cn.com.connext.scrm.utils.RedisUtils;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.req.CrmMemberReq;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.connext.common.exception.ServiceException;
import com.connext.common.util.date.DateTime;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional
public class MemberService extends BaseService<Member, String> {
    private static final String MTURL = "http://106.ihuyi.cn/webservice/sms.php?method=";//短信发送接口地址
    private static final String IMTURL = "http://api.isms.ihuyi.com/webservice/isms.php?method=";//国际短信发送地址
    private static final String SUBMIT = "Submit";
    private static final String GETNUM = "GetNum";
    private static final String APIID = "C63972255";//账号
    private static final String APIKEY = "3b9110054cd5c7ccf7174fc2dd22eb66";//密码
    private static final String IAPIID = "I35180961";//账号
    private static final String IAPIKEY = "63b25b8fccb42be6206d4d2bde97e310";//密码
    private static final int EFFECTIVE_TIME = 50;//有效时间，单位：秒
    private static final String key = "code-phone-";

    private final Logger log = LoggerFactory.getLogger(MemberService.class);
    private final MemberRepository memberRepository;
    private RestTemplate restTemplate = new RestTemplate();
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private AccessTokenImpl accessTokenImpl;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SendRecordRepository sendRecordRepository;

    @Autowired
    private MiniProgramUserRepository miniProgramUserRepository;

    @Value("${myapp.smsSend.daySendTimesLimit}")
    private String daySendTimesLimit;


    protected MemberService(MemberRepository memberRepository) {
        super(memberRepository);
        this.memberRepository = memberRepository;
    }

    /**
     * 查询一个会员
     *
     * @param membershipId
     * @return
     */
    public ResponseEntity<JSONObject> findOneDTO(String membershipId) {
        log.info("Request to get MemberInfo : {}", membershipId);
        ResponseEntity<JSONObject> memberDTO = null;
        //参数不为空
        if (null != membershipId) {
            //获取token
            String accessToken = accessTokenImpl.getAccessToken();

            //调用外部系统接口
            String requestUrl = Constants.FINDMemberInfoByMembershipIdUrl.replace("ACCESS_TOKEN", accessToken).replace("MEMBERSHIPID", membershipId);
            memberDTO = restTemplate.getForEntity(requestUrl, JSONObject.class);
        }
        return memberDTO;
    }

    /**
     * 根据 unionId 或手机号 查询会员是否存在
     * @param unionId
     * @param mobile
     * @return
     */
    public Member getMemberByUnionIdOrMobile(String unionId ,String mobile){
        return  memberRepository.findByUnionIdAndMobile(unionId, mobile);
    }

    /**
     * 保存会员信息
     */
    public JSONObject saveMemberInfo(MemberDTO memberDTO) {
        Member member = null;
        JSONObject result = new JSONObject();
        //数据不为空添加到数据库
        if (null != memberDTO) {
            member = memberMapper.toEntity(memberDTO);
            //todo unionid或moblie其中一项就认为会员已存在
            Member mbr = memberRepository.findByUnionIdAndMobile(member.getUnionId(), member.getMobile());
            if (mbr ==null || StringUtils.isEmpty(mbr.getMembershipId())) {
                //获取token
                String accessToken = accessTokenImpl.getAccessToken();
                //调用外部接口
                String requestUrl = Constants.MemberInfoSaveUrl.replace("ACCESS_TOKEN", accessToken);
                JSONObject requestBody = new JSONObject();

                requestBody.put("openid", member.getOpenId());
                requestBody.put("unionid", member.getUnionId());
                requestBody.put("mobile", member.getMobile());
                requestBody.put("img", member.getHeadImgUrl());
                requestBody.put("displayName", member.getNickName());
                SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
                requestBody.put("dateJoin", dateFormatGmt.format(new Date()));
                requestBody.put("source", member.getSource());
                requestBody.put("contentName", member.getContentName());
                log.info("注册会员请求参数：{}", requestBody.toString());
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(requestBody.toString(), headers);
                result = restTemplate.postForEntity(requestUrl, formEntity, JSONObject.class).getBody();
                log.info("注册会员信息result:{}", result);
                if ("0000".equals(result.getString("error_code"))) {
                    //查询会员信息是否存在
                    Member meb = memberRepository.findByUnionIdAndMobile(member.getUnionId(), member.getMobile());
                    if (null != meb) {
                        //修改会员信息
                        meb.setMembershipId(result.getString("membershipId"));
                        meb.setMobile(member.getMobile());
                        meb.setContentName(memberDTO.getContentName());
                        meb.setSkuId(memberDTO.getSkuId());
                        member = memberRepository.saveAndFlush(meb);
                        //会员授权信息表添加手机号
                        MiniProgramUser miniProgramUser = miniProgramUserRepository.findByUnionId(meb.getUnionId());
                        if (null != miniProgramUser) {
                            miniProgramUser.setPhone(member.getMobile());
                            miniProgramUserRepository.saveAndFlush(miniProgramUser);
                        }
                        log.info("修改保存结束", member);
                    } else {
                        //新增会员信息
                        member.setMembershipId(result.getString("membershipId"));
                        member.setTelephone(member.getMobile());
//                        member.setSkuId(memberDTO.getSkuId());
                        log.info("新增开始参数: {}", member);
                        member = memberRepository.saveAndFlush(member);
                        log.info("新增保存结束", member);
                        log.info("新增结束参数: {}", member);
                        result.put("用户信息",member.toString());
                    }
                }
            } else {
                if (null!= mbr.getMobile()&& mbr.getMobile().equals(member.getMobile())) {
                    result.put("error_code", "0002");
                    result.put("error_description", "当前手机号已注册会员");
                } else if (null!= mbr.getUnionId()&& mbr.getUnionId().equals(member.getUnionId())) {
                    result.put("error_code", "0002");
                    result.put("error_description", "当前微信已注册会员");
                }
//                result.put("error_code", "0002");
//                result.put("error_description", "该手机号已被注册");
            }
        }
        return result;
    }

    /**
     * 修改会员信息
     */
    public JsonResult update(CrmMemberReq req) {
        JsonResult jsonResult = new JsonResult();
        Member meber = memberRepository.findByUnionId(req.getUserId());
        if (null != meber && StringUtils.isNotBlank(meber.getMembershipId())) {
            //如果传入的用户生日信息不为空
            if(StringUtils.isNotEmpty(req.getBirthday())){
                SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
                dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
                if(meber.getBirthday() !=null){
                    String s = meber.getBirthday().toString();
                    String birthday = s.substring(0, s.indexOf("T"));
                    if(!birthday.equals(req.getBirthday())){
                        req.setC_birthdayUpdateDate(dateFormatGmt.format(new Date()));
                    }
                }else{
                    req.setC_birthdayUpdateDate(dateFormatGmt.format(new Date()));
                }
            }
            //获取token
            String accessToken = accessTokenImpl.getAccessToken();
            //修改会员信息
            String requestUrl = Constants.MemberInfoUpdateUrl.replace("MEMBERSHIPID", meber.getMembershipId()).replace("ACCESS_TOKEN", accessToken);
            log.info("修改会员信息requestUrl:{}", requestUrl);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            log.info("----------={}", JSON.toJSONString(req));
            HttpEntity formEntity = new HttpEntity(JSON.toJSONString(req), headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<JSONObject> resultEntity = restTemplate.exchange(requestUrl, HttpMethod.PUT, formEntity, JSONObject.class);
            JSONObject result = resultEntity.getBody();
            log.info("修改会员信息result:{}", result);
            if (!result.containsKey("error_code") && !result.containsKey("error")) {
                if (StringUtils.isNotBlank(req.getBirthday())) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    ZonedDateTime offsetDateTime = LocalDate.parse(req.getBirthday(), formatter).atStartOfDay().atZone(ZoneId.of("Asia/Shanghai"));
                    meber.setBirthday(offsetDateTime);
                }
                if (null != req.getGender()) {
                    meber.setGender(req.getGender());
                }
                if (StringUtils.isNotBlank(req.getProvince())) {
                    meber.setProvince(req.getProvince());
                }
                if (StringUtils.isNotBlank(req.getCity())) {
                    meber.setCity(req.getCity());
                }
                if (StringUtils.isNotBlank(req.getAddress())) {
                    meber.setAddress(req.getAddress());
                }
                if (StringUtils.isNotBlank(req.getImg())) {
                    meber.setHeadImgUrl(req.getImg());
                }
                if (StringUtils.isNotBlank(req.getName())) {
                    meber.setNickName(req.getName());
                }
                meber = memberRepository.saveAndFlush(meber);
                log.info("修改会员信息结束:{}", meber);
                jsonResult.setState(0);
                jsonResult.setData(meber);
                return jsonResult;
            }
            jsonResult.setState(1);
            log.info("修改会员信息结束result:{}", result);
            return jsonResult;
        }
        jsonResult.setState(1);
        jsonResult.setMessage("会员数据异常，请联系管理员");
        return jsonResult;
    }

    /**
     * 修改手机号
     *
     * @param memberDTO
     * @return
     */
    public JsonResult updateMobile(JSONObject memberDTO) {
        JsonResult jsonResult = new JsonResult();
        Member meber = memberRepository.findOneByUnionId(memberDTO.getString("userId"));
        if (null == meber) {
            jsonResult.setMessage("会员信息异常，请联系管理员");
            jsonResult.setState(1);
            return jsonResult;
        }
        if (StringUtils.isEmpty(meber.getMembershipId())) {
            meber.setTelephone(memberDTO.getString("newMobile"));
            meber = memberRepository.saveAndFlush(meber);
            log.info("修改会员手机号信息结束:{}", JSON.toJSONString(meber));
            jsonResult.setState(0);
            jsonResult.setData(meber);
            return jsonResult;
        }
        //获取token
        String accessToken = accessTokenImpl.getAccessToken();
        //修改会员手机号
        String requestMobileUrl = Constants.MemberMobileUpdateUrl.replace("ACCESS_TOKEN", accessToken);
        JSONObject requestMobileBody = new JSONObject();
        requestMobileBody.put("oldMobile", memberDTO.getString("oldMobile"));
        requestMobileBody.put("newMobile", memberDTO.getString("newMobile"));
        requestMobileBody.put("membershipId", meber.getMembershipId());
        log.info("修改会员手机号请求参数：{}", requestMobileBody.toString());
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(requestMobileBody.toString(), headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> resultEntity = restTemplate.exchange(requestMobileUrl, HttpMethod.PUT, formEntity, JSONObject.class);
        JSONObject result = resultEntity.getBody();
        if (!result.containsKey("error_code") || !result.containsKey("error")) {
            meber.setTelephone(memberDTO.getString("newMobile"));
            meber = memberRepository.saveAndFlush(meber);
            log.info("修改会员手机号信息结束:{}", JSON.toJSONString(meber));
            jsonResult.setState(0);
            jsonResult.setData(meber);
            return jsonResult;
        }
        log.info("修改会员手机号信息result:{}", result);
        jsonResult.setState(0);
        jsonResult.setData(result);
        return jsonResult;
    }


    /**
     * 校验手机号
     */
    public boolean isMobileNO(String mobile) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (mobile.length() != 11) {
            throw new ServiceException(MyErrorCode.ERROR_MOBILE_FORMAT);
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(mobile);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }

    /**
     * 发送短信验证码
     *
     * @param phone：手机号
     * @return：返回给前端的实体
     */
    public SmsDTO sendCodeSms(String phone) {
        phone = phone.trim();
        String[] phoneInfo = phone.split("-");
        if (phoneInfo.length > 1 && !StringUtils.equals(phoneInfo[0], "86")) {
            return sendISms(phoneInfo);
        }
        log.info("send code sms to {}", phone);
        SmsDTO smsDTO = new SmsDTO();

        if (StringUtils.isBlank(phone)) {
            smsDTO.setResult("2");
            smsDTO.setMessage("phone can't be empty!");
            return smsDTO;
        }
        if (sendTimesLimit(phone)) {
            smsDTO.setResult("5");
            smsDTO.setMessage("sent times limit!");
            return smsDTO;
        }
        //发送时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        //验证此号码是否刚刚请求发过短信，且是否已过有效期
        if (!MapUtil.validationPeriod(phone, timestamp.getTime(), EFFECTIVE_TIME)) {
            smsDTO.setResult("3");
            smsDTO.setMessage("can't send it again in " + EFFECTIVE_TIME + " seconds!");
            return smsDTO;
        }
        //随机6位数字的验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        smsDTO.setCode(code);
        smsDTO.setResult("0");
        smsDTO.setMessage("send code sms success");
//        new Thread(() -> {
        try {
            //短信内容
            String sm = new String("您的校验码为：【" + code + "】。为了保护您的账号安全，请勿把校验码提供给他人。");                //http请求对象创建
            Client client = Client.create();
            WebResource webResource = client.resource(MTURL + SUBMIT);
            //短信接口参数设置
            MultivaluedMapImpl formData = new MultivaluedMapImpl();
//                formData.add("method",METHOD);
            formData.add("account", APIID);
            formData.add("password", APIKEY);
            formData.add("mobile", phone);
            formData.add("content", sm);
            //post方式请求发送短信接口发送短信
            ClientResponse clientResponse = webResource.type(String.valueOf(MediaType.APPLICATION_FORM_URLENCODED)).post(ClientResponse.class, formData);
            //获取返回结果
            String textEntity = clientResponse.getEntity(String.class);


            log.info("sendCodeSms------mobile:{}------result:{}", phone, textEntity);
            //将返回结果转成map
            Document doc = DocumentHelper.parseText(textEntity);
            Element root = doc.getRootElement();

            //获取错误码
            String error_code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");

            //添加发送记录到数据库
            SendRecordEntity sendRecord = new SendRecordEntity();
            sendRecord.setReceivePhone(phone);
            sendRecord.setSendTime(timestamp);
            sendRecord.setCode(code);
            sendRecord.setMessage(sm);
            sendRecord.setResultMsg(textEntity);

            //若错误码为2表示发送成功
            if (StringUtils.equals(error_code, "2")) {
                sendRecord.setResult("0");
                String phoneKey = key + phone;
                log.info("redisKey:{}", phoneKey);
                if (redisUtils.exists(phoneKey)) {
                    redisUtils.remove(phoneKey);
                }
                redisUtils.set(phoneKey, code, 300L);
//                    smsDTO = sendCodeSmsMapper.toDto(sendRecord);
            } else {
                smsDTO.setResult("4");
                smsDTO.setMessage("send code sms fail：error_code:" + error_code + ",msg:" + msg);
                log.info("*************send code sms fail：error_code:{},msg:{}", error_code, msg);
            }
            sendRecordRepository.save(sendRecord);
        } catch (Exception e) {
            smsDTO.setResult("-1");
            smsDTO.setMessage("send code sms exception：" + e.getMessage());
            log.info("*************send code sms exception：{}", e);
        }
//        }).start();

        return smsDTO;
    }

    public SmsDTO sendISms(String[] phoneInfo) {
        log.info("send international sms to {}", phoneInfo.toString());
        SmsDTO smsDTO = new SmsDTO();
        if (StringUtils.isBlank(phoneInfo[1])) {
            smsDTO.setResult("2");
            smsDTO.setMessage("phone can't be empty!");
            return smsDTO;
        }
        String logPhone = phoneInfo[0] + "-" + phoneInfo[1];
        if (sendTimesLimit(logPhone)) {
            smsDTO.setResult("5");
            smsDTO.setMessage("sent times limit!");
            return smsDTO;
        }
        //发送时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        //验证此号码是否刚刚请求发过短信，且是否已过有效期
        if (!MapUtil.validationPeriod(phoneInfo[1], timestamp.getTime(), EFFECTIVE_TIME)) {
            smsDTO.setResult("3");
            smsDTO.setMessage("can't send it again in " + EFFECTIVE_TIME + " seconds!");
            return smsDTO;
        }
        //随机6位数字的验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        smsDTO.setCode(code);
        smsDTO.setResult("0");
        smsDTO.setMessage("send code international sms success");
//        new Thread(() -> {
        try {

            //短信内容
            String sm = new String("您的校验码为：【" + code + "】。为了保护您的账号安全，请勿把校验码提供给他人。");                //http请求对象创建

//            String sm = new String("您的验证码是：【" + code + "】。请不要把验证码泄露给其他人。");                //http请求对象创建
            Client client = Client.create();
            WebResource webResource = client.resource(IMTURL + SUBMIT);
            //短信接口参数设置
            MultivaluedMapImpl formData = new MultivaluedMapImpl();
//                formData.add("method",METHOD);
            formData.add("account", IAPIID);
            formData.add("password", IAPIKEY);
            formData.add("mobile", phoneInfo[0] + " " + phoneInfo[1]);
            formData.add("content", sm);
            //post方式请求发送短信接口发送短信
            ClientResponse clientResponse = webResource.type(String.valueOf(MediaType.APPLICATION_FORM_URLENCODED)).post(ClientResponse.class, formData);
            //获取返回结果
            String textEntity = clientResponse.getEntity(String.class);
            log.info("sendISms------mobile:{}------result:{}", logPhone, textEntity);
            //将返回结果转成map
            Document doc = DocumentHelper.parseText(textEntity);
            Element root = doc.getRootElement();

            //获取错误码
            String error_code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("ismsid");

            //添加发送记录到数据库
            SendRecordEntity sendRecord = new SendRecordEntity();
            sendRecord.setReceivePhone(logPhone);
            sendRecord.setSendTime(timestamp);
            sendRecord.setCode(code);
            sendRecord.setMessage(sm);
            sendRecord.setResultMsg(textEntity);
            //若错误码为2表示发送成功
            if (StringUtils.equals(error_code, "2")) {
                sendRecord.setResult("0");
                String phoneKey = key + logPhone;
                log.info("redisKey:{}", phoneKey);
                if (redisUtils.exists(phoneKey)) {
                    redisUtils.remove(phoneKey);
                }
                redisUtils.set(phoneKey, code, 300L);
//                    smsDTO = sendCodeSmsMapper.toDto(sendRecord);
            } else {
                sendRecord.setResult("4");
                smsDTO.setResult("4");
                smsDTO.setMessage("send code international  sms fail：error_code:" + error_code + ",msg:" + msg);
                log.info("*************send code international sms fail：error_code:{},msg:{}", error_code, msg);
            }
            sendRecordRepository.save(sendRecord);
        } catch (Exception e) {
            smsDTO.setResult("-1");
            smsDTO.setMessage("send code international sms exception：" + e.getMessage());
            log.info("*************send code international sms exception：{}", e);
        }
//        }).start();

        return smsDTO;
    }

    private Boolean sendTimesLimit(String mobile) {
        if (StringUtils.isEmpty(daySendTimesLimit)) {
            return false;
        }
        int limit = Integer.parseInt(daySendTimesLimit);
        if (limit == 0) {
            return false;
        }
        String today = new DateTime().toString("yyyy-MM-dd");
        Integer count = sendRecordRepository.getCountTodayByMobile(mobile, today);
        log.info("sendTimesLimit...mobile:{}...date:{}...count:{}", mobile, today, count);
        if (count >= limit)
            return true;
        return false;
    }

    /**
     * 验证验证码
     */
    public JSONObject sendSmsCode(JSONObject jsonObject) {
        JSONObject object = new JSONObject();
        String phoneKey = key + jsonObject.getString("phone");
        log.info("phoneKey:{}", phoneKey);
        if (redisUtils.exists(phoneKey)) {
            String code = String.valueOf(redisUtils.get(phoneKey));
            log.info("code:{}", String.valueOf(redisUtils.get(phoneKey)));
            if (code.equals(jsonObject.getString("code"))) {
                object.put("status", "success");
                object.put("msg", "验证码成功");
            } else {
                object.put("status", "error");
                object.put("msg", "验证码错误");
            }
        } else {
            object.put("status", "error");
            object.put("msg", "验证码失效");
        }
        return object;
    }

    /**
     * 根据会员身份查询会员信息
     */
    public ResponseEntity<JSONObject> getMembershipByIdentity(String value) {
        log.info("查询会员信息 : {}", value);
        //获取token
        String accessToken = accessTokenImpl.getAccessToken();
        //调用外部系统接口
        String requestUrl = Constants.GetMembershipByIdentityUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", "wechat-unionid").replace("VALUE", value);
        ResponseEntity<JSONObject> obj = restTemplate.getForEntity(requestUrl, JSONObject.class);
        log.info("根据会员身份查询会员信息：{}", obj.toString());
        if (!obj.getBody().containsKey("error")) {
            //更新MembershipId
            Member meber = memberRepository.findByUnionId(value);
            if(meber ==null){
                obj.getBody().put("state", -1);
                obj.getBody().put("message", "当前用户不存在");
                return obj;
            }
            meber.setMembershipId(obj.getBody().getJSONObject("membership").getString("id"));
            meber = memberRepository.saveAndFlush(meber);

            //得到 membership jsonobject
            JSONObject memberObj = obj.getBody().getJSONObject("membership");

            //获取成长值
            //获取token
            String accessTokenExp = accessTokenImpl.getAccessToken();
            //调用外部系统接口
            String expRequestUrl = Constants.GetExpChangeLogstUrl.replace("ACCESS_TOKEN", accessTokenExp).replace("MEMBERSHIPID", obj.getBody().getJSONObject("membership").getString("id"));
            ResponseEntity<JSONObject> objExp = restTemplate.getForEntity(expRequestUrl, JSONObject.class);
            log.info("根据会员MembershipId查询会员成长值信息：{}", objExp.toString());
            if (objExp.getBody().getJSONArray("rows").size() > 0) {
                memberObj.put("newExp", objExp.getBody().getJSONArray("rows").getJSONObject(0).getString("newExp"));
            } else {
                memberObj.put("newExp", null);
            }

            //获取有效期
            //获取token
            String accessTokenDateCreated = accessTokenImpl.getAccessToken();
            //调用外部系统接口
            String membershipLevelChangeLogsUrl = Constants.GetMembershipLevelChangeLogsUrl.replace("ACCESS_TOKEN", accessTokenDateCreated).replace("MEMBERSHIPID", obj.getBody().getJSONObject("membership").getString("id"));
            ResponseEntity<JSONObject> objDateCreated = restTemplate.getForEntity(membershipLevelChangeLogsUrl, JSONObject.class);
            log.info("根据会员MembershipId查询会员有效期信息：{}", objDateCreated.toString());
            if (objDateCreated.getBody().getJSONArray("rows").size() > 0) {
                if (!memberObj.getJSONObject("level").isEmpty()) {
                    if ("1".equals(memberObj.getJSONObject("level").getString("priority")) || "0".equals(memberObj.getJSONObject("level").getString("priority"))) {
                        memberObj.put("newDateCreated", "2990-12-30");//永久有效
                    } else if ("2".equals(memberObj.getJSONObject("level").getString("priority")) ||
                        "3".equals(memberObj.getJSONObject("level").getString("priority")) ||
                        "4".equals(memberObj.getJSONObject("level").getString("priority"))) {
                        // upd 会员有效期信息取时间最近的 王云祥 20210511 start
                        //memberObj.put("newDateCreated", getDate(objDateCreated.getBody().getJSONArray("rows").getJSONObject(0).getString("dateCreated")));//次年当月月底之前有效
                        memberObj.put("newDateCreated", getDate(objDateCreated.getBody().getJSONArray("rows").getJSONObject(objDateCreated.getBody().getJSONArray("rows").size() - 1).getString("dateCreated")));//次年当月月底之前有效
                        // upd 会员有效期信息取时间最近的 王云祥 20210511 end
                    }
                } else {
                    memberObj.put("newDateCreated", null);
                }
            } else {
                memberObj.put("newDateCreated", null);
            }

            //重新赋值
            obj.getBody().put("membership", memberObj);
        } else {
            //更新MembershipId
            Member meber = memberRepository.findByUnionId(value);
            meber.setMembershipId("");
            meber = memberRepository.saveAndFlush(meber);
        }
        log.info("根据会员身份信息查询会员信息结束");
        return obj;
    }

    /**
     * 获取次年当月月底
     */
    public static String getDate(String date) {
        String[] dateOld = date.split("-");

        int year = Integer.valueOf(dateOld[0]);
        int month = Integer.valueOf(dateOld[1]);

        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year + 1);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    public String findMemberShipIdByUnionId(String unionId) {
        Member member = memberRepository.findByUnionId(unionId);
        log.info("member:{}", JSON.toJSONString(member));
        if (member == null){
            return null;
        }
        if (StringUtils.isEmpty(member.getMembershipId())){
            return null;
        }
        return member.getMembershipId();
    }

    public Member findByUnionId(String unionId) {
        Member member = memberRepository.findByUnionId(unionId);
        return member;
    }

}
